﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;

namespace EmaMetadata
{
    public class EmaLookupTable
    {
        protected Dictionary<string, List<LookupItem>> _dict = new Dictionary<string,List<LookupItem>>();

        #region Interface
        /// <summary>
        /// Retrieve all the items matching the specified lookup table identity
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public List<LookupItem> GetLookups(string key)
        {
            List<LookupItem> list = null;
            if (!_dict.TryGetValue(key, out list)) {
                list = new List<LookupItem>();
            }
            return list;
        }

        /// <summary>
        /// Add a new lookup item to this table
        /// </summary>
        /// <param name="dict"></param>
        /// <param name="n"></param>
        public LookupItem AddItem(string LookupTableKey, string NS, int ID, string FactName, string Notes)
        {
            string key = (LookupTableKey).ToUpper();
            List<LookupItem> list = null;
            LookupItem li = new LookupItem() { NS = NS, ID = ID, FactName = FactName, Notes = Notes, Table = LookupTableKey };
            if (!_dict.TryGetValue(key, out list)) {
                list = new List<LookupItem>();
            }
            list.Add(li);
            _dict[key] = list;
            return li;
        }

        #endregion

        #region Load and save to XML
        public static EmaLookupTable Load(XmlDocument d)
        {
            EmaLookupTable t = new EmaLookupTable();
            Dictionary<string, List<LookupItem>> dict = new Dictionary<string, List<LookupItem>>();

            // Read in the data from this dictionary
            foreach (XmlNode n in d.DocumentElement.ChildNodes) {
                if (n.Name == "define") {
                    t.AddItem(n.ValueOrDefault("table"), n.ValueOrDefault("ns"), n.ValueOrDefaultInt("id"), n.ValueOrDefault("factname"), n.ValueOrDefault("notes"));
                }
            }

            // Here's what we were able to read in
            return t;
        }

        /// <summary>
        /// Save this lookup table to a file
        /// </summary>
        /// <param name="fn"></param>
        public void Save(string fn)
        {
            // Ensure the path exists
            Directory.CreateDirectory(Path.GetDirectoryName(fn));

            // Save the file
            using (XmlWriter xw = XmlWriter.Create(fn)) {
                xw.WriteStartElement("definitions");
                foreach (var kvp in _dict) {
                    xw.WriteWhitespace("\n");
                    xw.WriteComment(kvp.Key);
                    foreach (var li in kvp.Value) {
                        xw.WriteStartElement("define");
                        xw.WriteAttributeString("ns", li.NS);
                        xw.WriteAttributeString("table", kvp.Key);
                        xw.WriteAttributeString("id", li.ID.ToString());
                        xw.WriteAttributeString("factname", li.FactName);
                        if (!String.IsNullOrEmpty(li.Notes)) {
                            xw.WriteAttributeString("notes", li.Notes);
                        }
                        xw.WriteEndElement();
                    }
                }
                xw.WriteEndElement();
                xw.Close();
            }
        }
        #endregion
    }
}
